<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>重力感应</title>
</head>
<body>
    <form action="" oninput="c.value=100 - parseInt(speed1.value)">
        <label for="speed1">请设置阈值: </label><input type="number" value="30" name="speed" id="speed1">
    
        
        【当前灵敏度：<output name="c" for="x">70</output>】
        <br>
        <button type="button" onclick="f1()">测试</button>
    </form>
    
    <script>
        function f1(){
            var speed1 = document.getElementById("speed1").value
            if(window.DeviceMotionEvent) {
            var speed = speed1;    // 用来判定的加速度阈值，太大了则很难触发
            var x, y, z, lastX, lastY, lastZ;
            x = y = z = lastX = lastY = lastZ = 0;
                
            window.addEventListener('devicemotion', function(event){
                 var acceleration = event.accelerationIncludingGravity;
                 x = acceleration.x;
                 y = acceleration.y;
                 if(Math.abs(x-lastX) > speed || Math.abs(y-lastY) > speed) {
                    if(navigator.vibrate) {
                        navigator.vibrate(500)
                    }
                    alert("检测到您摇晃了手机");
                 }
                 lastX = x;
                 lastY = y;
            }, false);
        }
        }
        
    </script>
</body>
</html>
